<?php
/* tgtai_fcns.php
 * Perform various support functions for processing feeds
 *
*/

$mct_ai_log_domain;  //Keys for checking feed login
$mct_ai_log_opt; //login option values
$mct_ai_fdvals_tbl = $wpdb->base_prefix.'fdvals';

function mct_ai_check_feed($url){
    //Check this feed and see if it has login info, 
    //if so do the login and return the $cookie, and the caller gets the page
    //if no login info, return ''
    //if the login fails return Fail
    global $wpdb, $mct_ai_fdvals_tbl, $mct_ai_log_domain, $mct_ai_log_opt;

    if ($mct_ai_log_opt == "None") return '';
    
    if (empty($mct_ai_log_domain)){   //Glogal set?
        if (empty($mct_ai_log_opt)){  //global option set?
            $mct_ai_log_opt = get_option('mct_ai_log_opt');
            if ($mct_ai_log_opt == false){
                $mct_ai_log_opt = "None";  //No logins so set to None for next call
                return '';
            }
        }
        $idlist = '';
        foreach ($mct_ai_log_opt as $opt) {  //get list of ids to retrieve
            if (!empty($idlist)) $idlist .= ',';
            $idlist .= strval($opt['sid']);
        }
        //Comment out the where clause to get all ids, so we can fail if no user/pwd
        $sql = "SELECT fdv_id, fdv_domain FROM $mct_ai_fdvals_tbl WHERE fdv_id in ( $idlist )"; 
        $mct_ai_log_domain = $wpdb->get_results($sql,ARRAY_A);
    }
    $logid = 0;
    foreach ($mct_ai_log_domain as $dom){
        if (stripos($url,$dom['fdv_domain']) !== false) {
            $logid = $dom['fdv_id'];
            break;
        }
    }
    if (!$logid) return '';  //Not a login domain
    //Get auth strings
    $auth = array();
    foreach ($mct_ai_log_opt as $opt) { 
        if ($opt['sid'] != $logid) continue;
        $auth['user'] = $opt['uname'];
        $auth['pass'] = $opt['pass'];
        break;
    }
    if (empty($auth)) {
        mct_ai_log('blog',MCT_AI_LOG_ERROR, 'No Login for Feed: ',$url);
        return 'Fail';  //No user/pwd for this domain, so don't even try
    }
    return mct_ai_common_prep($logid,$auth);
}

function mct_ai_common_prep($logid, $auth){
    //Prepare for login by getting values from DB for $logid, using passed in $auth array with uname and pass
    
    global $wpdb, $blog_id, $mct_ai_fdvals_tbl; 
    
    //Get login info
    $sql = "SELECT * FROM $mct_ai_fdvals_tbl WHERE fdv_id = $logid";
    $logstr = $wpdb->get_row($sql,ARRAY_A);
    if (!$logstr) return 'Fail';
    
  
    $post_str = $logstr['fdv_ustr'].$auth['user'].'&'.$logstr['fdv_pstr'].$auth['pass'];
    $cookie = ABSPATH.'mct-sl-savelink'.'/'.$blog_id.'-'.$logstr['fdv_cookie'];
    $reg_url = $logstr['fdv_regurl'];
    $faildom = $logstr['fdv_faildom'];

    //Call custom function if there, otherwise common login
    if (!empty($logstr['fdv_func'])) {
        $func = $logstr['fdv_func'];
        $ret = $func($logstr['fdv_ustr'],$logstr['fdv_pstr'],$auth,$reg_url,$cookie, $faildom);
    } else {
        $ret = mct_ai_common_login($faildom,$reg_url, $post_str, $cookie);
    }
    if ($ret) {
        return $cookie;  //return cookie file if success for future page reads
    } else {
        return 'Fail';
    }
}

function mct_ai_common_login($fail_dom,$reg_url, $poststr,$cookie){
    //Do  a 1 step login using passed in values
    // INIT CURL
    $ch = curl_init();
    // SET URL FOR THE POST FORM LOGIN
    curl_setopt($ch, CURLOPT_URL, $reg_url);
    // ENABLE HTTP POST
    curl_setopt ($ch, CURLOPT_POST, 1);
    // Don't worry about certificate
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_AUTOREFERER, true);
    // SET POST PARAMETERS : FORM VALUES FOR EACH FIELD
    curl_setopt ($ch, CURLOPT_POSTFIELDS, $poststr);
    // IMITATE CLASSIC BROWSER'S BEHAVIOUR : HANDLE COOKIES
    $agent = "Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.4) Gecko/20030624 Netscape/7.1 (ax)";
    curl_setopt($ch, CURLOPT_USERAGENT, $agent);
    curl_setopt ($ch, CURLOPT_COOKIEJAR, $cookie);
    curl_setopt ($ch, CURLOPT_COOKIEFILE, $cookie);
    //Force curl to return results and not display
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    // EXECUTE FORM LOGIN
    $store = curl_exec ($ch);
    $ret = curl_getinfo($ch);
    curl_close($ch);
    if ($ret == false) {
        mct_ai_log('blog',MCT_AI_LOG_ERROR, 'Curl Failed',$reg_url);
        return false;
    }
    if ($ret['http_code'] != 200) {
        mct_ai_log('blog',MCT_AI_LOG_ERROR, 'HTTP error: '.strval($ret['http_code']),$reg_url);
        return false;
    } 
    if (stripos($ret['url'],$fail_dom) !== false) {
        mct_ai_log('blog',MCT_AI_LOG_ERROR, 'Could not log in',$reg_url);
        return false;
    }
    return true;  
}

//Custom NYT Login function - first get hidden fields, then do common login
function mct_ai_nyt_login($ustr,$pstr,$auth,$regurl,$cookie, $faildom){

    // SET URL FOR THE POST FORM LOGIN and get the hidden fields
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $regurl);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $agent = "Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.4) Gecko/20030624 Netscape/7.1 (ax)";
    curl_setopt($ch, CURLOPT_USERAGENT, $agent);
    curl_setopt ($ch, CURLOPT_COOKIEJAR, $cookie);
    curl_setopt ($ch, CURLOPT_COOKIEFILE, $cookie);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    // EXECUTE 1st REQUEST (get FORM LOGIN)
    $store = curl_exec ($ch);
    //Save the hidden tokens
    $token = stripos($store,'name="token" value="');
    $tval = substr($store,$token+20,32);
    $exp = stripos($store,'name="expires" value="');
    $eval = substr($store,$exp+22,10);
    curl_close($ch);
    //Now set up the post str
    $post_str = $ustr.$auth['user'].'&'.$pstr.$auth['pass'].'&is_continue=false&token='.$tval.'&expires='.$eval;
    
    return mct_ai_common_login($faildom,$regurl, $post_str, $cookie);
}

//Page to display the form
function mct_ai_feed_logins() {
    
    global $wpdb, $mct_ai_fdvals_tbl;
    
    if ($_GET['updated'] == 'true'){
        $msg = 'Logins Updated';
    }
    if (isset($_POST['Submit']) ) {
        $cnt = $_POST['fld_cnt'];
        $opt_update = array();
        for ($i=0; $i < $cnt; $i++) {
            if (isset($_POST['uname'.$i]) && isset($_POST['pname'.$i]) && strlen(trim($_POST['uname'.$i])) > 0 && strlen(trim($_POST['pname'.$i])) > 0){
                $opt_update[] = array(
                    'sid' => $_POST['sid'.$i],
                    'uname' => trim($_POST['uname'.$i]),
                    'pass' => trim($_POST['pname'.$i])
                );
            }
        }
        
        update_option('mct_ai_log_opt',$opt_update);
    }
    //Get all of the sites and the current option values from options
    $sql = "SELECT fdv_id, fdv_name FROM $mct_ai_fdvals_tbl ORDER BY fdv_name ASC";
    $sites = $wpdb->get_results($sql,ARRAY_A);
    $cur_options = get_option('mct_ai_log_opt');
    $cnt = count($sites);
    
    ?>
<div class='wrap'>
    <?php screen_icon('link-manager'); ?>
    <h2>Feed Logins</h2>
    <?php 
    if (!empty($msg)){ ?>
       <div id=”message” class="updated" ><p><strong><?php echo $msg ; ?></strong></p></div>
    <?php } ?>
    <p>For feeds from sources where you have a login, enter the username and password below.</p>
    <h3>You are responsible for having the appropriate accounts to distribute articles to users of your site!</h3>
    <form method="post" action="<?php echo $_SERVER['REQUEST_URI'] . '&updated=true"'; ?> >
        <input name="fld_cnt" type="hidden" value="<?php echo $cnt; ?>" />
        <table class="widefat" >
            <thead>
                <tr>
                <th>Site</th>
                <th>Username</th>
                <th>Password</th>
                </tr>
            </thead>
            <tbody>
            <?php $i = 0;  foreach ($sites as $site) { 
                $sid = $site['fdv_id'];
                //Set dynamic input names
                $sidname = 'sid'.strval($i);
                $uname = 'uname'.strval($i);
                $pname = 'pname'.strval($i);
                //Set user/pwd fields
                $userstr = '';
                $pwdstr = '';
                foreach ($cur_options as $cur){
                    if ($cur['sid'] == $sid) {
                        $userstr = $cur['uname'];
                        $pwdstr = $cur['pass'];
                    }
                }
            ?>
            <tr>
                <th scope="row"><?php echo $site['fdv_name']; ?></th>
                <input name="<?php echo $sidname; ?>" type="hidden" value="<?php echo $sid; ?>" />
                <td><input type ="text" maxlength="50" size ="30" name="<?php echo $uname; ?>" value ="<?php echo $userstr ?>" /></td>
                <td><input type ="password" maxlength="50" size ="30" name="<?php echo $pname; ?>" value ="<?php echo $pwdstr ?>" /></td>
            </tr> 
            <?php $i++; } ?>
            </tbody>
        </table>
        <div class="submit">
            <input name="Submit" type="submit" value="Save Options" class="button-primary" />
        </div>
        </form>
</div>
<?php
}

function mct_ai_log($topic, $type, $msg, $url){
    global $wpdb, $ai_logs_tbl;
    
    $ins_array = array(
                'logs_date' => current_time('mysql'),
                'logs_topic' => $topic,
                'logs_type' => $type,
                'logs_url' => $url,
                'logs_msg' => $msg
            );
    $wpdb->insert($ai_logs_tbl, $ins_array);
    
}

function mct_ai_tw_expandurl($url){
    //Expand the passed in url and return it    
    $ch = curl_init($url);
    curl_setopt($ch,CURLOPT_HEADER,true);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch,CURLOPT_NOBODY,true);    
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION,true);
    $headers = curl_exec($ch);
    curl_close($ch);
    if (preg_match_all('/Location:\s(.+?\s)/i', $headers, $matches)) {
        $pos = count($matches[1]) - 1;
        $url = trim($matches[1][$pos]);
    }
    return $url;
}


?>
